import React, { useEffect, useState } from 'react'
import { PageHeader, Table, Space, Button, Modal, notification } from 'antd'
import axios from 'axios';
import {
  DeleteOutlined,
  EditOutlined,
  UploadOutlined,
  ExclamationCircleOutlined
 } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

const { confirm } = Modal;

export default function Newsdraft() {
  let {username} = JSON.parse(localStorage.getItem('token'));
  const [dataSource, setDataSource] = useState([]);
  const navigate = useNavigate();
  useEffect(()=>{
    axios({
      url:`/news?auditState=0&_expand=category&author=${username}`
    }).then(res => {
      console.log(res.data);
      setDataSource(res.data);
    })
  },[username])
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: '新闻标题',
      dataIndex: 'title',
      render:(title, item)=>{
        // eslint-disable-next-line jsx-a11y/anchor-has-content
        return (
          <a href={`/sandbox/news/preview/${item.id}`}>{title}</a>
        )
      }
    },
    {
      title: '作者',
      dataIndex: 'author',
    },
    {
      title: '分类',
      dataIndex: 'category',
      render:(category) => {
        return category.title;
      }
    },
    {
      title: '操作',
      render:(item) => {
        return (
          <Space size="middle">
            <Button danger shape="circle" icon={<DeleteOutlined />} size='small' onClick={()=>{
              deleteDraft(item);
            }}/>
            <Button type='primary' shape="circle" icon={<EditOutlined />} size='small' onClick={()=>{
              navigate(`/sandbox/news/update/${item.id}`);
            }}/>
            <Button type='primary' shape="circle" icon={<UploadOutlined />} size='small' onClick={()=>{
              jumptoAudit(item.id);
            }}/>
          </Space>
        )
      }
    },
  ];
  const deleteDraft = (item) =>{
    confirm({
      title: '您确定要删除这一权限吗？',
      icon: <ExclamationCircleOutlined />,
  
      onOk() {
        let list = dataSource;
          list = list.filter((data)=> data.id !== item.id)
          setDataSource(list);
          axios({
            url:`/news/${item.id}`,
            method:'DELETE'
          })
      },

      onCancel() {
        console.log('Cancel');
      },
    })
  }
  const jumptoAudit = (id) => {
    axios.patch(`/news/${id}`,{
      auditState:1
    }).then(()=>{
      navigate('/sandbox/audit/list');
      notification.info({
        message: `消息提示`,
        description:
          '本条新闻已成功提交至审核列表',
      });
    })
  }
  return (
    <div>
      <PageHeader
        className="site-page-header"
        title="草稿箱"
      />
      <Table dataSource={dataSource} columns={columns} rowKey={item => item.id}/>
    </div>
  )
}
